package com.joysuch.wwyt.mh.controller;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.mh.bean.MhMajorHazardPlanSearchBean;
import com.joysuch.wwyt.mh.bean.vo.MajorHazardPlanDeleteCheckVO;
import com.joysuch.wwyt.mh.bean.vo.MhMajorHazardPlanVO;
import com.joysuch.wwyt.mh.dto.MhMajorHazardPlanDTO;
import com.joysuch.wwyt.mh.entity.MhMajorHazardPlan;
import com.joysuch.wwyt.mh.service.MhMajorHazardPlanService;
import com.joysuch.wwyt.repeatsubmit.NoRepeatSubmit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zqw
 * @since 2022-05-17
 */
@RestController
@RequestMapping("/mh/major-hazard-plan")
@Api(tags = "重大危险源计划")
public class MhMajorHazardPlanController {


    @Autowired
    private MhMajorHazardPlanService planService;

    @PostMapping("/savePlan")
    @ApiOperation("保存危险源计划")
    @NoRepeatSubmit(paramNames = "planName")
    @RequiresPermissions("mh:major-hazard-plan:savePlan")
    public ResultBean savePlan(@RequestBody MhMajorHazardPlanDTO dto) {
        MhMajorHazardPlan plan = planService.savePlan(dto);
        return ResultBean.success(plan);
    }

    @PostMapping("/pagePlan")
    @ApiOperation("危险源计划分页")
    public ResultBean pagePlan(@RequestBody MhMajorHazardPlanSearchBean searchBean) {
        return planService.pagePlan(searchBean);
    }

    @GetMapping("/findById")
    @ApiOperation("查看危险源计划")
    public ResultBean findById(Long id) {
        MhMajorHazardPlanVO vo = planService.findById(id);
        return ResultBean.success(vo);
    }

    @GetMapping("/deleteById")
    @ApiOperation("删除危险源计划")
    @RequiresPermissions("mh:major-hazard-plan:deleteById")
    public ResultBean deleteById(Long id) {
        try {
            planService.deleteById(id);
        } catch (ApiBusinessException e) {
            if (e.getCode() == Status.DELETE_CHECK_FAILED.getCode() && e.getMessage() != null) {
                List<MajorHazardPlanDeleteCheckVO> list = Lists.newArrayList();
                MajorHazardPlanDeleteCheckVO vo = JSONObject.parseObject(e.getMessage(), MajorHazardPlanDeleteCheckVO.class);
                list.add(vo);
                return ResultBean.fail(e.getCode(), "", list);
            } else {
                return ResultBean.fail(e.getCode(), e.getMessage());
            }
        }


        return ResultBean.success("");
    }
}

